package com.hqyj.lyf.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * shiro配置类，替代了之前的shiro.xml文件
 */
@Configuration
public class MyShiroConfig {
    // 1.密码匹配器
    @Bean("hashedCredentialsMatcher")
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hcm = new HashedCredentialsMatcher();
        // 设置加密算法
        hcm.setHashAlgorithmName("MD5");
        // 设置加密次数
        hcm.setHashIterations(1024);
        return hcm;
    }

    // 2.指定自己的realm
    @Bean("myShiroRealm")
    public MyShiroRealm getMyShiroRealm(@Qualifier("hashedCredentialsMatcher")HashedCredentialsMatcher hcm) {
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        myShiroRealm.setCredentialsMatcher(hcm);
        return myShiroRealm;
    }

    // 3.配置安全管理器
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getSecurityManager(@Qualifier("myShiroRealm")MyShiroRealm myShiroRealm){
        DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
        // 注入自己定义的shiro认证授权规则
        dwsm.setRealm(myShiroRealm);
        return dwsm;
    }

    // 4.shiro过滤拦截规则
    @Bean
    public ShiroFilterFactoryBean getShiroFilter(@Qualifier("securityManager") DefaultWebSecurityManager sm){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        // 注入安全管理器
        bean.setSecurityManager(sm);

        //配置登录页面（未登陆去往的页面）
        bean.setLoginUrl("/");

        //配置权限页面（没有权限去往的页面）
        bean.setUnauthorizedUrl("/unauthorized");


        //配置权限的map
        HashMap<String, String> map = new HashMap<>();
        // authc anon role[] perms[]
        map.put("/","anon"); // 登录页面，都可以访问
        map.put("/user/login","anon"); // 登录方法都可以访问
        map.put("/index","authc"); // index页面必须登录了才可以访问
        map.put("/static/**","anon"); // 静态资源都可以访问
        map.put("/**","anon"); // 以上拦截规则都不匹配则放行
        // 设置过滤拦截规则
        bean.setFilterChainDefinitionMap(map);
        return bean;
    }

    // 5.开启html页面使用shiro标签
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

    // 6.声明周期控制
    @Bean
    public LifecycleBeanPostProcessor getProcess(){
        return new LifecycleBeanPostProcessor();
    }

}
